package com.linkage.jz.bankruptcy.activity.Person;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.linkage.jz.bankruptcy.BankruptcyApp;
import com.linkage.jz.bankruptcy.Consts;
import com.linkage.jz.bankruptcy.R;
import com.linkage.jz.bankruptcy.activity.Main.CreateAddrActivity;
import com.linkage.jz.bankruptcy.adapter.MyAddrViewAdapter;
import com.linkage.jz.bankruptcy.base.BaseActivity;
import com.linkage.jz.bankruptcy.bean.MyAddr;
import com.linkage.jz.bankruptcy.utils.SPUtils;
import com.linkage.jz.bankruptcy.widget.Divider;
import com.linkage.jz.bankruptcy.widget.MyCommonDialog;
import com.linkage.jz.bankruptcy.widget.ShapeLoadingDialog;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Random;

import cn.bingoogolapple.androidcommon.adapter.BGAOnItemChildClickListener;
import cn.bingoogolapple.androidcommon.adapter.BGAOnItemChildLongClickListener;
import cn.bingoogolapple.androidcommon.adapter.BGAOnRVItemClickListener;
import cn.bingoogolapple.androidcommon.adapter.BGAOnRVItemLongClickListener;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


/**
 *
 * A login screen that offers login via email/password.
 *
 *
 */


public  class PersonSettingAddrActivity extends BaseActivity implements OnClickListener , BGAOnRVItemClickListener, BGAOnRVItemLongClickListener, BGAOnItemChildClickListener, BGAOnItemChildLongClickListener {
    private static final String TAG = PersonSettingAddrActivity.class.getSimpleName();
    private TextView text,top_mune1;
    //    private static final String TAG = RecyclerViewDemoActivity.class.getSimpleName();
    private MyAddrViewAdapter mAdapter;
    private ArrayList<MyAddr> mData;
    private RecyclerView mDataRv;
    private MyCommonDialog dialog;
    private ShapeLoadingDialog shapeLoadingDialog ;

    @Override
    public void initData() {

    }

    @Override
    public void setListener() {
//        r_tru.setOnClickListener(this);
        top_back.setOnClickListener(this);
        top_mune1.setOnClickListener(this);
    }

    @Override
    public void initTitle() {
        top_title = findViewById(R.id.top_title);
        top_title.setText("我的地址");
        top_mune.setVisibility(View.INVISIBLE);
        top_mune1.setText("新增");
        top_mune1.setVisibility(View.INVISIBLE);
    }

    @Override
    public void initView() {

    }


    TextView top_title,tv_ver;
    Button top_back,top_mune;
    RelativeLayout r_tru,r_getver;

    public static void start(Context context) {
        Intent intent = new Intent(context, PersonSettingAddrActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        setContentView(R.layout.activity_my_addr);

        initview();
        shapeLoadingDialog = new ShapeLoadingDialog(this);
//        tv_ver.setText(Utils.getLocalVersionName(this));
//        init(view);
        initRecyclerView();
        getData();

        super.onCreate(savedInstanceState);
    }

    //初始化视图
    private void initview() {
        //登录层、下拉层、其它登录方式层
//        r_tru = findViewById(R.id.r_tru);
//        r_getver = findViewById(R.id.r_getver);
//        tv_ver = findViewById(R.id.tv_ver);
        top_back = findViewById(R.id.top_back);
        top_mune = findViewById(R.id.top_mune);
        top_mune1 = findViewById(R.id.top_mune1);

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.top_back:
                finish();
                break;
            case R.id.r_tru:
                PersonSettingReadMeActivity.start(this);
                break;

            case R.id.top_mune1:
//                getVer();
//                getTest(s);

                Intent i=new Intent(PersonSettingAddrActivity.this,CreateAddrActivity.class);
                //返回数据
                startActivityForResult(i,1);
                break;

            default:
                break;
        }
    }

    private void initRecyclerView() {
        mDataRv = (RecyclerView) findViewById(R.id.rv_recyclerview_data);
        mDataRv.addItemDecoration(new Divider(this));

        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mDataRv.setLayoutManager(layoutManager);

        mAdapter = new MyAddrViewAdapter(mDataRv);
        mAdapter.setOnRVItemClickListener(this);
        mAdapter.setOnRVItemLongClickListener(this);
        mAdapter.setOnItemChildClickListener(this);
        mAdapter.setOnItemChildLongClickListener(this);

        mDataRv.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                if (RecyclerView.SCROLL_STATE_DRAGGING == newState) {
                    mAdapter.closeOpenedSwipeItemLayoutWithAnim();
                }
            }
        });
        mData = new ArrayList<MyAddr>();
//        mData = DataEngine.loadNormalModelDatas();
        mAdapter.setData(mData);
        mDataRv.setAdapter(mAdapter);
    }

    @Override
    public void onItemChildClick(ViewGroup parent, View childView, int position) {
        if (childView.getId() == R.id.tv_item_bgaswipe_delete) {
            mAdapter.closeOpenedSwipeItemLayoutWithAnim();
            mAdapter.removeItem(position);
        }
    }

    @Override
    public boolean onItemChildLongClick(ViewGroup parent, View childView, int position) {
        if (childView.getId() == R.id.tv_item_bgaswipe_delete) {
//            Toast.makeText(getActivity(), "长按了删除 " + mAdapter.getItem(position).getTitle(), Toast.LENGTH_SHORT).show();
            return true;
        }
        return false;
    }

    @Override
    public void onRVItemClick(ViewGroup parent, View itemView, int position) {
//        Toast.makeText(getActivity(), "点击了条目 " + mAdapter.getItem(position).getTitle(), Toast.LENGTH_SHORT).show();
    }

    @Override
    public boolean onRVItemLongClick(ViewGroup parent, View itemView, int position) {
//        Toast.makeText(getActivity(), "长按了条目 " + mAdapter.getItem(position).getTitle(), Toast.LENGTH_SHORT).show();
        return true;
    }


    public void getData()
    {
        if(BankruptcyApp.tokeninfo == null|| BankruptcyApp.tokeninfo.getToken() == null)
        {
            getToken();
            return;
        }
//        shapeLoadingDialog.setLoadingText("加载中...");
//        shapeLoadingDialog.setCanceledOnTouchOutside(false);
//        shapeLoadingDialog.show();
        OkHttpClient okHttpClient = new OkHttpClient();
//        HashMap<String, String> params = new HashMap<String, String>();
        Random random = new Random();
        String rom = random.nextLong()+"";
        String timestamp =System.currentTimeMillis()+"";
        String userToken = SPUtils.getInstance(Consts.SPNAME).getString("userToken","");
        String userId = SPUtils.getInstance(Consts.SPNAME).getString("userId","");

        RequestBody requestBody = new FormBody.Builder()
                .add("appid","1000000001")
                .add("nonce",rom)
                .add("timestamp", timestamp)
                .add("token", BankruptcyApp.tokeninfo.getToken())
                .add("userId",userId)
                .add("userToken",userToken)
                .build();

        String url = Consts.WEBURL_GETADDR;
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                shapeLoadingDialog.dismiss();
//                Log.d(TAG, "onFailure: " + e.getMessage());
                runOnUiThread(new Runnable(){
//
                    @Override
                    public void run() {
                        //更新UI
                        Toast.makeText(PersonSettingAddrActivity.this,"保存失败",Toast.LENGTH_SHORT).show();

                    }

                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
//                Log.d(TAG, response.protocol() + " " +response.code() + " " + response.message());
//                Headers headers = response.headers();
//                shapeLoadingDialog.dismiss();
//                for (int i = 0; i < headers.size(); i++) {
//                    Log.d(TAG, headers.name(i) + ":" + headers.value(i));
//                }


                String str = response.body().string();
                try{
                    JSONObject object = new JSONObject(str);
                    mData.clear();
                    if(object.optInt("code") == 0)
                    {
//                        JSONObject data = object.getJSONObject("data");
                        JSONArray ary = object.getJSONArray("data");
                        for(int i=0;i<ary.length();i++)
                        {
                            JSONObject data = ary.getJSONObject(i);
                            MyAddr model = new MyAddr();
                            model.setAddress(data.getString("address"));
                            model.setCity(data.getString("city"));
                            model.setDefaut(data.getBoolean("defaut"));
                            model.setProvince(data.getString("province"));
                            model.setRegion(data.getString("region"));
                            model.setZipCode(data.getString("zipCode"));
                            mData.add(model);
                        }
                        runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                //更新UI
                                mAdapter.notifyDataSetChanged();

                            }

                        });

                    }else {

                    }
                    str = "";
                }catch (Exception ex)
                {
                    ex.printStackTrace();
                }
            }
        });
    }


}

